package com.wendal.java.happydog.action;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;

import com.wendal.java.happydog.HappyDogContent;

public class BuyFoodAction extends AbstractAction{

	public static final String FOOD_5 = "1"; 
	public static final String FOOD_20 = "2";
	public static final String FOOD_40 = "3";
	
	private static final String ActionURL = "http://dog.kaixin.com/store.do";
	
	private HappyDogContent content;
	@Override
	public void execute(HappyDogContent content, Object... args) {
		if(args == null || args.length != 1) return;
		String foodType = String.valueOf(args[0]);
		if(foodType.matches("[1-3]")){
			this.content = content;
			buyFood(foodType);
		}
	}

	protected void buyFood(String foodType) {
		try {
			Map<String, String> keyValue = new HashMap<String, String>();
			keyValue.put("buy_count", "1");
			keyValue.put("buy_id", foodType);
			keyValue.put("method", "buyfood");
			keyValue.put("tsc", content.getTsc());
			String result = content.getClientVM().accessURL_Post(ActionURL,keyValue ,"UTF-8");
			if(JSONUtils.mayBeJSON(result)){
				JSONObject object = JSONObject.fromObject(result);
				if(object.getBoolean("result") == true){
					log.info("购买成功, " +
							"食物数="+object.getString("foods")+", " +
							"骨头数="+object.getString("bones"));
				}else{
					log.info("购买失败!");
				}
			}else{
				log.info("结果不是JSon,购买失败!");
			}
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}
}
